﻿using System.Text.RegularExpressions;
using System.ServiceModel.Configuration;
using System.Configuration;
using System;
namespace SmallERP.COM
{
    public static class MondifyConfig
    {
        public static int Modify(string path, string newIP)
        {
            int rtnVal = 0;
            try
            {
                Configuration config = ConfigurationManager.OpenExeConfiguration(path);
                ConfigurationSectionGroup sct = config.SectionGroups["system.serviceModel"];
                ServiceModelSectionGroup serviceModelSectionGroup = sct as ServiceModelSectionGroup;
                ClientSection clientSection = serviceModelSectionGroup.Client;
                foreach (ChannelEndpointElement item in clientSection.Endpoints)
                {
                    string pattern = "://.*/";
                    string address = item.Address.ToString();
                    string oldHost=item.Address.Host;
                    if (oldHost.Equals(newIP))
                    {
                        rtnVal = 1;//不要改变
                        break;
                    }
                    string replacement = string.Format("://{0}:{1}/", newIP, 7892);
                    address = Regex.Replace(address, pattern, replacement);
                    item.Address = new Uri(address);
                }
                config.Save(ConfigurationSaveMode.Modified);
                ConfigurationManager.RefreshSection("system.serviceModel");
            }
            catch (Exception ex)
            {
                rtnVal=-1;
            }
            return rtnVal;
        }
    }
}
